package com.example.userserver.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.commons.entity.MessageplatfromDO;
import com.example.commons.entity.TrainingCertificatesDO;
import com.example.commons.entity.UserDO;
import com.example.commons.utils.*;
import com.example.commons.vo.LoginUserVo;
import com.example.commons.vo.LoginVo;
import com.example.commons.vo.SendSmsVo;
import com.example.userserver.config.RedisUtil;
import com.example.userserver.service.SchoolCertificatesService;
import com.example.userserver.service.UserService;
import com.example.userserver.sms.server.MessageplatfromService;
import com.example.userserver.sms.server.TrainingCertificatesService;
import com.example.userserver.sms.smssend.SmsSendServer;
import com.example.userserver.util.CertificateUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/jinZhiIndex/userServer")
public class UserServiceController  {

    @Autowired
    private UserService userService;
    @Autowired
    private SmsSendServer sendServer;
    @Autowired
    private TrainingCertificatesService trainingCertificatesService;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private MessageplatfromService messageplatfromService;

    @Autowired
    private SchoolCertificatesService schoolCertificatesService;

    @GetMapping("/getUser")
    @ResponseBody
    ApiResult<?> getUserInfo() {

      UserDO userDO=  JWTUtil.getUser();

        return ApiResult.success(userDO);
    }


    @PostMapping("/loginNu")
    @ResponseBody
    ApiResult<?> ajaxLogin(@RequestBody LoginUserVo loginUserVo) {

        UsernamePasswordToken token = new UsernamePasswordToken(loginUserVo.getUsername(), loginUserVo.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            UserDO userDO = (UserDO) subject.getPrincipals().getPrimaryPrincipal();
            //根据手机号码生成自定义登录态
            String returnToken = userService.getToken(  userDO.getMobile());
            //将生成的登录态和手机号码关联，并存到缓存中
            Map cache = new HashMap();
            cache.put("mobile", userDO.getMobile());
           // EhCacheUtil.put(returnToken.getToken(), cache);
            //返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            map.put("token", returnToken);
            map.put("userName", userDO.getUsername());
            map.put("type", userDO.getType());
            map.put("uName", userDO.getName());
          //  req.getSession().setAttribute("userName", userDO.getUsername());
            return ApiResult.success(map);
        } catch (AuthenticationException e) {
            return ApiResult.fail("登录错误！");
        }
    }


    @PostMapping("/loginPass")
    @ResponseBody
    Object ajaxLogin(String username, String password) {
        String pass=  MD5Utils.convertMD5(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, pass);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return ApiResult.fail();
        }
        return ApiResult.success();
    }

    @PostMapping("/login")
    public Object login( LoginVo loginVo){
        Map map =new HashMap();
        if(loginVo.getWxId()==null){
            return ApiResult.fail("参数为空！");
        }
        if(StringUtils.isBlank(loginVo.getCode())){
            return ApiResult.fail("参数为空！");
        }
        map.put("wxId",loginVo.getWxId());
        map.put("encryptedData",loginVo.getEncryptedData());
        map.put("iv",loginVo.getIv());
        map.put("code",loginVo.getCode());
        AtomicInteger atomicIntege=new AtomicInteger();
        atomicIntege.getAndIncrement();
        Object token=   userService.login(map);
        return ApiResult.success(token);
    }

    /**
     * 用于获取信息
     * @param token
     * @return
     */
    @PostMapping("getUserInfo")
    public Object getMemberInfo(String token) {
        if(StringUtils.isBlank(token)){

            return ApiResult.fail("未登录！");
        }
        //调用jwt工具类的方法，根据request对象获取头信息，返回对象id
//        if(redisUtil.get(token)==null){
//            return ApiResult.fail("用户不存在");
//        }
       // String userid=  redisUtil.get(token).toString();;
        //查询数据库根据用户id获取用户数据
        UserDO member = userService.getById(JWTUtil.getUser().getId());

        if(member==null){
            return ApiResult.fail("用户不存在");
        }

        return ApiResult.success(member);

    }
    /**
     * api小程序端-发送注册验证短信
     *
     * @Description: 调取短信平台发送短信，参数： 微信端口id，手机号码
     * @Param: [wxId, mobile]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-06-20
     */
    @PostMapping("/sendSms")
    @ApiOperation(value = "api小程序端-发送注册验证短信", httpMethod = "POST")
    public ApiResult<?> sendSms( String mobile) {
        //第一步验证手机号格式
        if (!ValidUtils.isMobile(mobile)) {
            return ApiResult.format("mobile");
        }
        QueryWrapper<MessageplatfromDO> wrapper=new QueryWrapper();
        wrapper.like("smsDemo","SMS_186380670");

      List<MessageplatfromDO>   messageplatfromDO =   messageplatfromService.list(wrapper);

        Object redis= redisUtil.get(mobile);

        if(redis!=null){
            return ApiResult.fail("发送频繁，请休息一下！");
        }
        if(messageplatfromDO != null&&messageplatfromDO.size()>0){

            sendServer.send(mobile ,messageplatfromDO.get(0).getSmsDemo());
        }else{
            return ApiResult.fail("短信模板错误，请联系管理员！");
        }
        return ApiResult.success("发送成功");
    }
    /**
     *
     退出登录接口
     */
    @PostMapping("/userSignOut")
    public ApiResult<?> userSignOut(String token) {
       // redisUtil.del(token);
        return ApiResult.success();
    }
//    /**
//     *
//     退出登录接口
//     */
    @PostMapping("/testMobile")
    public ApiResult<?> testMobile(String mobile) {
        redisUtil.set(mobile+RedisUtil.code,"111",200);
        return ApiResult.success();
    }
    /**
     *
     退出登录接口
     */
    @PostMapping("/getMobileTime")
    public ApiResult<?> getMobileTime(SendSmsVo mobile) {

        System.out.println();
        return ApiResult.success(redisUtil.getExpire(mobile+RedisUtil.code));
    }


    /**
     *
     * @Param: [wxId, mobile]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-06-20
     */
    @PostMapping("/sendLogin")
    // @ApiOperation(value = "api小程序端-发送注册验证短信", httpMethod = "POST")
    public ApiResult<?> mobileLogin(SendSmsVo sendSmsVo) {
        sendSmsVo.setAccount(sendSmsVo.getMobile());
        if (StringUtils.isBlank(sendSmsVo.getCode())) {
            return ApiResult.lack("code");
        } else {
            //第二步，判断验证码
            try {
                String rediskey=sendSmsVo.getMobile()+RedisUtil.code;
                String mobileCode= (String) redisUtil.get(rediskey);


                if(!mobileCode.equals(sendSmsVo.getCode())){
                    return ApiResult.fail("验证码错误");
                }
            } catch (Exception e) {
                return ApiResult.build(ApiEnumError.apiSmsCodeInvalid.getCode(), ApiEnumError.apiSmsCodeInvalid.getMsg());
            }
            //第三步，根据手机号码获取用户信息并判断，如没有则新建，如果则返回信息
            QueryWrapper<UserDO> wrapper=new QueryWrapper();
            wrapper.like("mobile",sendSmsVo.getAccount());
            List<UserDO> userDOS=    userService.list(wrapper);
            UserDO userDO = new UserDO();
            if (userDOS.size()==0) {
                userDO.setUsername(sendSmsVo.getAccount());//默认手机号为新建账号的初始用户名
                userDO.setWxId(sendSmsVo.getWxId());
                userDO.setMobile(sendSmsVo.getAccount());
                //设置默认密码
                String salt = UUIDUtils.get();
                String passwd = PasswdUtils.get(null, salt);
                userDO.setSalt(salt);
                userDO.setPassword(passwd);
                userDO.setType(0);//默认个人会员
                userDO.setMoney(BigDecimal.valueOf(0.0));//默认0元
                userDO.setGmtCreate(new Date());
                userDO.setGmtModified(userDO.getGmtCreate());
                userDO.setStatus(1);//默认正常
                userDO.setSex(0L);//默认未知
                List<Long> list = new ArrayList<>();
                list.add(56L);
              boolean b=  userService.save(userDO);
                userDOS.add(userDO);
               // userDOS.get(0) = userDO;
            }

            //第四步，根据手机号码生成自定义登录态
            String returnToken = userService.getToken(sendSmsVo.getAccount());
            //第五步，将生成的登录态和手机号码关联
            Map cache = new HashMap();
            cache.put("mobile", sendSmsVo.getAccount());

            //第六步，返回登录态和用户信息
            Map<String, Object> map = new HashMap<>();
            //20200701 pjr新增isOpenId
            if (sendSmsVo.getWxId().equals(101)) {
                if (StringUtils.isBlank(userDOS.get(0).getCerOpenId())) {
                    map.put("isOpenId", false);//没有OpenId
                } else {
                    map.put("isOpenId", true);//有OpenId
                }
            } else if (sendSmsVo.getWxId().equals(102)) {
                if (StringUtils.isBlank(userDOS.get(0).getTraOpenId())) {
                    map.put("isOpenId", false);
                } else {
                    map.put("isOpenId", true);
                }
            }
            map.put("token",returnToken);
            map.put("userId", userDOS.get(0).getId());
            map.put("userName", userDOS.get(0).getUsername());
            map.put("headPortrait", userDOS.get(0).getHeadPortrait());
            return ApiResult.success(map);

        }
    }


    /**
     * api小程序端-证书查询--公开方法，不需要登录
     *
     * @Description: 根据证书编号查询证书信息，参数：证书编号
     * @Param: [certificateNo]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     */
    @PostMapping("/selCertificateDetails")
    // @Log("api小程序端-证书查询")
    public ApiResult<?> selCertificateDetails(Long id) {
        Map map=new HashMap();

        map.put("orgName","湖南金职伟业母婴护理有限公司");
        TrainingCertificatesDO certificatesDO=  trainingCertificatesService.getById(id);
        if(certificatesDO==null){
            return ApiResult.fail("未查询到数据");
        }
        map.put("certificateNumber",certificatesDO.getNumbers());
        map.put("time",certificatesDO.getGetTime());
        map.put("certificateName", CertificateUtil.comNumber1(certificatesDO.getNumbers(),certificatesDO.getNumbers()));
        map.put("img",certificatesDO.getImgUrl());
        UserDO userDO=   userService.getById(certificatesDO.getUserId());
        if(userDO==null){

            map.put("name","未绑定");
            map.put("idCard","未绑定");
        }else {
            map.put("name",userDO.getName());
            map.put("idCard",userDO.getIdNumber());
        }

        map.put("pinYin",CertificateUtil.toPinyin(userDO.getName()));
       return ApiResult.success(map);

    }
    /**
     * api小程序端-证书查询--公开方法，不需要登录
     *
     * @Description: 根据证书编号查询证书信息，参数：证书编号
     * @Param: [certificateNo]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     */
    @PostMapping("/selCertificate")
    // @Log("api小程序端-证书查询")
    public ApiResult<?> selCertificate(String idCard,String name) {

        if( StringUtils.isBlank(idCard)){
            return    ApiResult.fail("请输入身份证号码");
        }
       if( StringUtils.isBlank(name)){
        return    ApiResult.fail("请输入姓名");
        }

        //第一步，根据证书编号查询证书jz_training_certificates
        QueryWrapper<UserDO> wrapper=new QueryWrapper();
        wrapper.eq("idNumber",idCard);
        wrapper.eq("name",name);
        List<UserDO>  user = userService.list(wrapper);
        List<TrainingCertificatesDO>  certificList =new ArrayList<>();
        for(UserDO li:user){
            List <TrainingCertificatesDO> certificatesDOIs0 = new ArrayList<>();

            QueryWrapper<TrainingCertificatesDO> wrapper1=new QueryWrapper();
            wrapper1.eq("user_id",li.getId());

            List <TrainingCertificatesDO> certificatesDO = trainingCertificatesService.list(wrapper1);
            for (int i=0;i<certificatesDO.size();i++){
                if ("0".equals(String.valueOf(certificatesDO.get(i).getState()))){
                    TrainingCertificatesDO trainingCertificatesDO = new TrainingCertificatesDO();
                    trainingCertificatesDO.setId(certificatesDO.get(i).getId());
                    trainingCertificatesDO.setUserName(certificatesDO.get(i).getUserName());
                    trainingCertificatesDO.setUserId(certificatesDO.get(i).getUserId());
                    trainingCertificatesDO.setCoursesName(certificatesDO.get(i).getCoursesName());
                    trainingCertificatesDO.setCoursesId(certificatesDO.get(i).getCoursesId());
                    trainingCertificatesDO.setNumbers(certificatesDO.get(i).getNumbers());
                    trainingCertificatesDO.setOrgName(certificatesDO.get(i).getOrgName());
                    trainingCertificatesDO.setGetTime(certificatesDO.get(i).getGetTime());
                    trainingCertificatesDO.setImgUrl(certificatesDO.get(i).getImgUrl());
                    trainingCertificatesDO.setImgUrlNosale(certificatesDO.get(i).getImgUrlNosale());
                    trainingCertificatesDO.setQueries(certificatesDO.get(i).getQueries());
                    trainingCertificatesDO.setState(certificatesDO.get(i).getState());
                    trainingCertificatesDO.setCertificatesType(certificatesDO.get(i).getCertificatesType());
                    certificatesDOIs0.add(trainingCertificatesDO);
                }
            }
            if(certificatesDOIs0.size()>0){
                List<TrainingCertificatesDO> collect = certificatesDOIs0.stream().sorted(Comparator.comparing(TrainingCertificatesDO::getGetTime,Comparator.reverseOrder())).collect(Collectors.toList());
                certificList.addAll(collect);
            }
        }
        DateTimeFormatter df =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map> mapList=new ArrayList<>();
        if (certificList.size()>0) {
            for(TrainingCertificatesDO certificatesDO :certificList){
                Map map = new HashMap();
                map.put("cerImg",certificatesDO.getImgUrl());//证书图片
                map.put("certificatesType",certificatesDO.getCertificatesType()!=null?certificatesDO.getCertificatesType():"职业技能证书");//证书类型
                map.put("type", numIntType(certificatesDO.getCertificatesType()));
                map.put("certificateNo", certificatesDO.getNumbers());//证书编号
                map.put("addTime",  df.format(certificatesDO.getGetTime()));//获证时间
                map.put("isEffective", certificatesDO.getState());//证书是否有效,0有效，1无效
                map.put("grade", "见上图");
                map.put("id", certificatesDO.getId());
                map.put("name",user.get(0).getName());
                //第四步，添加查询次数
                int queries = certificatesDO.getQueries() + 1;
                certificatesDO.setQueries(queries);
                trainingCertificatesService.updateById(certificatesDO);
                mapList.add(map);
            }
            //第五步，封装返回map，并返回数据


        } else {
            return ApiResult.fail("身份证号码未查询到绑定账户！");
        }
        return ApiResult.success(mapList);
    }

        public Integer numIntType(String certificatesType){
               int i=0;
             if(certificatesType.contains("考务技术员")){
                 i=7;
             }else if(certificatesType.contains("督导员")){
                 i=6;
             }else if(certificatesType.contains("高级考评员")){
                 i=5;
             }else if(certificatesType.contains("考评员")&&!certificatesType.contains("高级考评员")){
                 i=4;
             }else if(certificatesType.contains("高级师资")){
                 i=3;
             }else if(certificatesType.contains("职业技能证书")){
                 i=2;
             }else {
                 i=1; //其他证书
             }

        return i;
        }

    /**
     * 试点院校站点相关荣誉证书查询
     */
    @GetMapping("/selSiteCertificate")
    public ApiResult<?> selSiteCertificate(String orgName){
        Map parameterMap =new HashMap();
        parameterMap.put("orgName",orgName);
        String key = redisUtil.createRediskey(parameterMap, "selSiteCertificate");
        List ca = (List) redisUtil.get(key);
        if (ca != null){
        //    System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++试点院校站点相关荣誉证书查询进入缓存");
            return ApiResult.success(ca);
        }
        QueryWrapper wrapper =new QueryWrapper();
        wrapper.in("org_name",orgName);
        List list = schoolCertificatesService.list(wrapper);
        redisUtil.set(key,list,86400); //一天过期
        return ApiResult.success(list);
    }
}
